const listBox = document.querySelector('.list')
const bsModal = new bootstrap.Modal(document.getElementById('modal'))
let studentId = 0
//====操作数据 - 和服务器打交道====
//1.向服务器获取学生列表数据
async function getStudentsData() {
    try {
        let res = await axios({ url: '/students' })
        return res
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '获取学生数据异常，请检查网络')
    }
}
//2.完成学生编辑功能
//2.1获取省 - 无参
async function getProvinceData() {
    try {
        let res = await axios({ url: '/api/province' })
        return res.data
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '获取省份数据异常，请检查网络')
    }
}
//2.2获取市 - 需要传入省名称
async function getCityData(pname) {
    try {
        let res = await axios({ url: '/api/city?pname=' + pname })
        return res.data
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '获取市区数据异常，请检查网络')
    }
}
//2.3获取区 - 需要传入省和市名称
async function getAreaData(pname, cname) {
    try {
        let res = await axios({ url: `/api/area?pname=${pname}&cname=${cname}` })
        return res.data
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '获取地区数据异常，请检查网络')
    }
}
//2.4根据id获取学生的详情老数据
async function getStudentInfoData(id) {
    try {
        let res = await axios({ url: `/students/${id}` })
        return res.data
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '获取学生数据异常，请检查网络')
    }
}
//2.5修改学生的详细数据
async function putStudentInfoData(id, body) {
    try {
        let res = await axios({ url: `/students/${id}`, method: 'PUT', data: body })
        return res
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '修改学生数据异常，请检查网络')
    }
}
//2.6新增学生数据
async function addStudentInfoData(body) {
    try {
        let res = await axios({ url: `/students`, method: 'POST', data: body })
        return res
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '修改学生数据异常，请检查网络')
    }
}
//2.7删除学生数据
async function removeStudentInfoData(id) {
    try {
        let res = await axios({ url: `/students/${id}`, method: 'DELETE' })
        return res
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '修改学生数据异常，请检查网络')
    }
}
//====渲染数据 - 和界面打交道====
//1.渲染学生数据到表格中
async function renderStudents() {
    let { data } = await getStudentsData()
    console.log(data)
    document.querySelector('.total').innerHTML = data.data.length
    // document.querySelector('.mb-0 .text-sm .font-weight-bold .username').innerHTML = localStorage.getItem('uname')
    let str = ''
    data.data.forEach(item => {
        str += `
        <tr>
            <td>${item.name}</td>
            <td>${item.age}</td>
            <td>${item.gender == 0 ? '男' : '女'}</td>
            <td>第${item.group}组</td>
            <td>${item.hope_salary}</td>
            <td>${item.salary}</td>
            <td>${item.province}${item.city}${item.area}</td>
            <td>
                <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"  data-id='${item.id}'></i></a>
                <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id='${item.id}'></i></a>
            </td>
        </tr>
        `
    })
    listBox.innerHTML = str
}
//2.渲染省，市，区三个数据到界面上
const provinceBox = document.querySelector('[name=province]')
async function renderProvince() {
    const { list } = await getProvinceData()
    let str = ''
    list.forEach(item => {
        str += `<option value="${item}">${item}</option>`
    })
    provinceBox.innerHTML = `<option value="">--省份--</option>${str}`
}

const cityBox = document.querySelector('[name=city]')
async function renderCity(pname) {
    const { list } = await getCityData(pname)
    let str = ''
    list.forEach(item => {
        str += `<option value="${item}">${item}</option>`
    })
    cityBox.innerHTML = `<option value="">--城市--</option>${str}`
}

const areaBox = document.querySelector('[name=area]')
async function renderArea(pname, cname) {
    const { list } = await getAreaData(pname, cname)
    let str = ''
    list.forEach(item => {
        str += `<option value="${item}">${item}</option>`
    })
    areaBox.innerHTML = `<option value="">--地区--</option>${str}`
}
//====各种事件 - 和用户打交道====
//1.1编辑事件
function registerClickHanderForTbody() {
    listBox.addEventListener('click', async function (e) {
        if (e.target.className === 'bi bi-pen') {
            document.querySelector('.modal-title').innerText = '修改学员'
            //数据回显
            studentId = e.target.dataset.id
            const { data } = await getStudentInfoData(studentId)
            console.log(data)

            for (key in data) {
                if (key === 'gender') {
                    const genderBox = document.querySelectorAll(`[name=${key}]`)
                    genderBox[data[key]].checked = true
                } else {
                    const box = document.querySelector(`[name=${key}]`)
                    if (box) {
                        box.value = data[key]
                    }
                }
            }
            //用户所在的省市区
            let { province, city, area } = data

            provinceBox.value = province

            await renderCity(province)
            cityBox.value = city

            await renderArea(province, city)
            areaBox.value = area

            bsModal.show()
        }
        if (e.target.className === 'bi bi-trash') {
            alert('确认删除?')
            await removeStudentInfoData(e.target.dataset.id)
            //成功提示
            pxmu.success('删除成功')
            //刷新列表数据
            renderStudents()
        }
    })

}
//1.2新增事件
function addClickHanderForTbody() {
    document.querySelector('#openModal').addEventListener('click', function (e) {
        if (e.target.className === 'bi bi-plus bi-2x') {
            document.querySelector('.modal-title').innerText = '新增学员'
            bsModal.show()
        }
    })
}
//2.注册省份和市区select的change事件
provinceBox.addEventListener('change', function (e) {
    let pname = e.target.value
    renderCity(pname)
})

cityBox.addEventListener('change', function (e) {
    let cname = e.target.value
    renderArea(provinceBox.value, cname)
})

const btnSubmitBox = document.querySelector('#submit')
const formBox = document.querySelector('#form')
btnSubmitBox.addEventListener('click', async function (e) {
    let body = serialize(formBox, { hash: true, empty: true })
    body.age = +body.age
    body.gender = +body.gender
    body.group = +body.group
    body.hope_salary = +body.hope_salary
    body.salary = +body.salary
    console.log(body);
    if (studentId > 0) {
        // 调用putStudentInfoData完成数据的修改
        await putStudentInfoData(studentId, body)
        //  关闭模态框
        bsModal.hide()
        //刷新列表数据
        renderStudents()
        studentId = 0
    } else {
        await addStudentInfoData(body)
        //  关闭模态框
        bsModal.hide()
        //成功提示
        pxmu.success('新增成功')
        //刷新列表数据
        renderStudents()
    }
})
//====进入页面时，各方法调用初始化====
renderStudents()
renderProvince()
registerClickHanderForTbody()
addClickHanderForTbody()